#include "Project.h"

#include <Serialization/Serialization.h>
#include <fstream>
#include <Log/Log.h>
#include <fstream>

namespace Engine2D
{
    void Project::NewProject(const std::string &fileName)
    {
        auto proj = std::shared_ptr<Project>(new Project());
        proj->m_projectName = fileName;
        proj->m_sceneName = std::filesystem::path(fileName).parent_path().append("defualt.scene").string();
        s_activeProj = proj;
        // auto node = Serialization::Serialize(*s_activeProj);
        // std::ofstream file(s_activeProj->m_projectName);
        // if (file.is_open()) {
        //     file << node;
        //     file.close();
        // }
    }

    void Project::OpenProject(const std::string &fileName)
    {
        auto node =  YAML::LoadFile(fileName);
        s_activeProj = std::shared_ptr<Project>(new Project(Serialization::DeSerialize<Project>(node)));
    }

    void Project::SaveProject(std::shared_ptr<Engine2D::Scene> scene)
    {
        auto node = Serialization::Serialize(*s_activeProj);
        std::ofstream fileProj(s_activeProj->m_projectName);
        if (fileProj.is_open()) {
            fileProj << node;
            fileProj.close();
        }
        node = Serialization::SerializeScene(scene);
        std::ofstream fileScenen(s_activeProj->m_sceneName);
        if (fileScenen.is_open()) {
            fileScenen << node;
            fileScenen.close();
        }
    }

    std::shared_ptr<Scene> Project::CreateScene()
    {
        assert(s_activeProj);
        try {
            YAML::Node node = YAML::LoadFile(s_activeProj->m_sceneName);
            return Serialization::DeSerializeScene(node);
        } catch(const std::exception& e) {
            LOG_ERROR("{}", e.what());
            LOG_INFO("Create New Empty Scene");
            return std::make_shared<Scene>();
        }
    }

} // namespace Engine2D
